#include "config.h"

QDomElement Config::getConfigRoot()
{
    QDomElement root;
    QFile *file = new QFile(QCoreApplication::applicationDirPath()+mConfPath);
    if(file->exists())
    {
        if(file->open(QIODevice::ReadOnly|QFile::Text))
        {
            QDomDocument doc;
            QString errorStr;
            int errorLine;
            int errorColumn;
            if(!doc.setContent(file,false,&errorStr,&errorLine,&errorColumn))
            {
                qDebug()<<"config xml has error in line:"<<errorLine<<" column:"<<errorColumn<<" because "<<errorStr;
                file->close();
                delete file;
            }else
            {
                file->close();
                delete file;
                root = doc.documentElement();
            }
        }else
        {
            qDebug()<<"open file error";
        }
    }else
    {
        qDebug()<<"config file dose not exist";
    }
    return root;
}

void Config::readDBInfo(QDomElement dbRoot)
{
    QDomNode node = dbRoot.firstChild();
    QString dbnameStr = node.toElement().text();
    node = node.nextSibling();
    QString hostnameStr = node.toElement().text();
    node = node.nextSibling();
    QString portStr = node.toElement().text();
    node = node.nextSibling();
    QString usernameStr = node.toElement().text();
    node = node.nextSibling();
    QString passwordStr = node.toElement().text();
    mDBInfo = new DBInfo();
    mDBInfo->dbname = dbnameStr;
    mDBInfo->hostname = hostnameStr;
    mDBInfo->port = portStr.toInt();
    mDBInfo->username = usernameStr;
    mDBInfo->password = passwordStr;
}

Config::Config(QString confPath)
{
    this->mConfPath = confPath;
    QDomElement root = getConfigRoot();//获取配置xml根节点
    QDomNode dbRoot = root.namedItem("db");
    readDBInfo(dbRoot.toElement());//读取数据库配置信息
}

void Config::setConfPath(QString confPath)
{
    this->mConfPath = confPath;
}

DBInfo* Config::getDBInfo()
{
    return mDBInfo;
}
